package com.aviccxzx.smarthome.fragment;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.UserModule.NewSceneAct;
import com.aviccxzx.smarthome.UserModule.RecommedSceneAct;
import com.aviccxzx.smarthome.UserModule.SceneDetailAct;
import com.aviccxzx.smarthome.entity.GetSceneBean;
import com.aviccxzx.smarthome.entity.SceneListAskBean;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.netutil.msg.MsgListener;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aviccxzx.smarthome.R.id.add_scene_img;
import static com.aviccxzx.smarthome.R.id.footer_view;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.subList;


public class SceneFragment extends Fragment {
    ListView scene_list;
    SwipeRefreshLayout layout_swipe_refresh;
    ImageView delete_scene_img;
    TextView no_scene;
    boolean deleteScene = false;
    SceneAdapter adapter = null;
    /**
     * 存储器
     */
    public SharedPreferences spf;
    /**
     * 存储器默认名称
     */
    public static final String SPF_Name = "set";
    int[] imgs = new int[]{R.mipmap.alarm_icon, R.mipmap.water_icon, R.mipmap.smoke_icon, R.mipmap.gas_icon, R.mipmap.door_icon, R.mipmap.video_icon};
    List<GetSceneBean.DataBean> sceneList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.scene_fragment, container, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view = inflater.inflate(R.layout.scene_fragment_v19, container, false);
        }
        return view;

    }

    private ProgressDialog progressDialog;

    public void showProgressDialog(String msg) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        try {
            progressDialog.show();
        } catch (WindowManager.BadTokenException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 取消对话框显示
     */
    public void disMissDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        deleteScene = false;
        if (subList.size() > 0) {
            //有子设备后才能有场景的存在，也才能进行添加场景的操作
            getSceneList();
        } else {
            //            App.getApp().showToast("您还没有子设备哦");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        deleteScene = false;
        adapter.notifyDataSetChanged();
    }

    SceneListAskBean scene = null;

    public void getSceneList() {
        showProgressDialog("加载中...");
        String uid = spf.getString("Uid", "");
        String Mac = spf.getString("gatemac", "");
        String imei = spf.getString("Imei", "");
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Gson gson = new Gson();
        /*{
                "imei":"string",
                "mac":"string",
                "uid":"string",
        }*/
        scene = new SceneListAskBean();
        scene.setImei(imei);
        scene.setMac(Mac);
        scene.setUid(uid);

        String strEntity = gson.toJson(scene);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        Call<GetSceneBean> call = service.getSceneList(body);
        call.enqueue(new Callback<GetSceneBean>() {
            @Override
            public void onResponse(Call<GetSceneBean> call, Response<GetSceneBean> response) {
                sceneList.clear();
                if (response != null && response.body() != null && response.body().getData() != null) {
                    sceneList = response.body().getData();
                }
                if (sceneList != null && sceneList.size() > 0) {
                    adapter.notifyDataSetChanged();
                    scene_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(getActivity(), SceneDetailAct.class);
                            intent.putExtra("sceneId", sceneList.get(i - 1).getScene_id());
                            intent.putExtra("sceneSwitch", sceneList.get(i - 1).getScene_switch() + "");
                            intent.putExtra("sceneName", sceneList.get(i - 1).getScene_name());
                            startActivity(intent);
                        }
                    });
                } else {
                    disMissDialog();
                }
            }

            @Override
            public void onFailure(Call<GetSceneBean> call, Throwable t) {
                disMissDialog();
            }
        });
        //        disMissDialog();
    }

    View header = null;
    View footer;
    LinearLayout recomendView;

    private void initView() {

        spf = getActivity().getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);
        delete_scene_img = (ImageView) getView().findViewById(R.id.delete_scene_img);
        no_scene = (TextView) getView().findViewById(R.id.no_scene);
        layout_swipe_refresh = (SwipeRefreshLayout) getView().findViewById(R.id.layout_swipe_refresh);
        scene_list = (ListView) getView().findViewById(R.id.scene_list);

        adapter = new SceneAdapter();

        header = LayoutInflater.from(getActivity()).inflate(R.layout.scenelist_header_lay, null);
        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //                App.getApp().showToast("tou");
            }
        });
        scene_list.addHeaderView(header);
        footer = LayoutInflater.from(getActivity()).inflate(R.layout.scenelist_footer_lay, null);
        recomendView = (LinearLayout) getView().findViewById(footer_view);
        footer.findViewById(R.id.footer_click_relativ).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), RecommedSceneAct.class);
                startActivity(intent);
            }
        });
        footer.findViewById(R.id.footer_notclick).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
        if (sceneList != null && sceneList.size() > 0) {

        } else {
            scene_list.addFooterView(footer);
        }
        getView().findViewById(add_scene_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (subList.size() > 0) {
                    Intent intent = new Intent(getActivity(), NewSceneAct.class);
                    startActivity(intent);
                } else {
                    App.getApp().showToast("您还没有添加子设备");
                }
            }
        });
        delete_scene_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sceneList.size() > 0) {
                    deleteScene = !deleteScene;
                    adapter.notifyDataSetChanged();
                }
            }
        });
        scene_list.setAdapter(adapter);
        layout_swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getSceneList();
                layout_swipe_refresh.setRefreshing(false);
            }
        });
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                getSceneList();
            }
        }, "scene");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                footer.setVisibility(View.GONE);
            }
        }, "recomend");
    }


    public class SceneAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return sceneList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View convertView, ViewGroup viewGroup) {
            View view = null;

            if (convertView != null) {
                view = convertView;
            } else {
                view = LayoutInflater.from(getActivity()).inflate(R.layout.scene_listitem_lay, viewGroup, false);
            }

            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                view.setTag(holder);
            }
            holder.scene_list_switch = (CheckBox) view.findViewById(R.id.scene_list_switch);
            holder.scene_list_delete = (ImageView) view.findViewById(R.id.scene_list_delete);
            holder.scene_item_name = (TextView) view.findViewById(R.id.scene_item_name);
            holder.diveceImgs_ll = (LinearLayout) view.findViewById(R.id.diveceImgs_ll);

            holder.diveceImgs_ll.removeAllViews();  //clear linearlayout
            for (int j = 0; j < sceneList.get(i).getDevice_types().size(); j++) {
                ImageView imageView = new ImageView(getActivity());
                imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));  //设置图片宽高
                if (sceneList.get(i).getDevice_types().get(j) != null) {
//                    imageView.setImageResource(imgs[sceneList.get(i).getDevice_types().get(j) - 1]); //图片资源
                    if (sceneList.get(i).getDevice_types().get(j) - 1 == 2) {
                        //烟感时 要区分新旧烟感
                        Set<String> newSmoke = spf.getStringSet("newSmoke", null);
                        if (newSmoke.size()>0){
                            //如果有新烟感，就设置为新烟感的图片，如果只有一个烟感时这种方法可行，新旧烟感都有就失效了，临时的补救方法。
                            imageView.setImageResource(R.mipmap.smoke_icon_hm);
                        }
                    } else {
                        imageView.setImageResource(imgs[sceneList.get(i).getDevice_types().get(j) - 1]); //图片资源
                    }
                }
                if (j < 4) {
                    holder.diveceImgs_ll.addView(imageView); //动态添加图片
                }
            }

            if (!TextUtils.isEmpty(sceneList.get(i).getScene_name())) {
                holder.scene_item_name.setText(sceneList.get(i).getScene_name());
            }
            if (sceneList.get(i).getScene_switch() == 1) {
                holder.scene_list_switch.setChecked(true);
            } else {
                holder.scene_list_switch.setChecked(false);
            }

            if (deleteScene) {
                holder.scene_list_switch.setVisibility(View.GONE);
                holder.scene_list_delete.setVisibility(View.VISIBLE);
                holder.scene_list_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //                            deleteScene = false;
                        //                        adapter.notifyDataSetChanged();

                        new DialogUtil(getActivity(), true, true, "确定要删除该场景吗?", "取消", "确定", new DialogUtil.SureInterfance() {
                            @Override
                            public void sureTodo() {
                                RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
                                Gson gson = new Gson();

                                String strEntity = gson.toJson(scene);

                                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
                                String id = sceneList.get(i).getScene_id();
                                Call<ResponseBody> call = service.deleteScene(body, id);
                                call.enqueue(new Callback<ResponseBody>() {
                                    @Override
                                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                        sceneList.remove(sceneList.get(i));
                                        notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                                        App.getApp().showToast("删除失败");
                                    }
                                });
                            }

                            @Override
                            public void cancle() {

                            }
                        }).showCustomDialog();
                    }
                });
            } else {
                holder.scene_list_delete.setVisibility(View.GONE);
                holder.scene_list_switch.setVisibility(View.VISIBLE);
                holder.scene_list_switch.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (sceneList.get(i).getScene_model() == 2) {
                            if (((CheckBox) view).isChecked()) {
                                //                                App.getApp().showToast("场景" + i + "开启");
                                setSceneSwitch(1, i);
                            } else {
                                //                                App.getApp().showToast("场景" + i + "关闭");
                                setSceneSwitch(0, i);
                            }
                        } else {
                            if (((CheckBox) view).isChecked()) {
                                ((CheckBox) view).setChecked(false);
                            } else {
                                ((CheckBox) view).setChecked(true);
                            }
                            App.getApp().showToast("自动模式下不能手动设置开关");
                        }
                    }
                });
            }
            disMissDialog();
            return view;
        }

        public void setSceneSwitch(int key, final int num) {
            RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
            Call<ResponseBody> call = service.setSceneSwitch(sceneList.get(num).getScene_id(), key);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    App.getApp().showToast("设置成功");
                    sceneList.get(num).setScene_switch(1);
                    //                    adapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    App.getApp().showToast("设置失败");
                    sceneList.get(num).setScene_switch(0);
                    //                    adapter.notifyDataSetChanged();
                }
            });
        }

        public class ViewHolder {
            ImageView scene_list_delete;
            CheckBox scene_list_switch;
            TextView scene_item_name;
            LinearLayout diveceImgs_ll;
        }
    }
}
